package cn.iocoder.moyun.framework.quartz.config;

import com.alibaba.ttl.TtlRunnable;
// TransmittableThreadLocal (TTL) 这个阿里开源项目。
//✔自动把 ThreadLocal 上下文从父线程“复制”到子线程，比如异步任务、线程池任务等。
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 异步任务 Configuration
 * 配置Spring异步任务执行器，集成TransmittableThreadLocal(TTL)实现线程上下文传递
 */
@AutoConfiguration
@EnableAsync
public class YudaoAsyncAutoConfiguration {
    @Bean
    public BeanPostProcessor threadPoolTaskExecutorBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                if (!(bean instanceof ThreadPoolTaskExecutor)) {
                    return bean;
                }
                // 修改提交的任务，接入 TransmittableThreadLocal
                ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
                // 把当前线程的 ThreadLocal 信息传递到异步线程中
                executor.setTaskDecorator(TtlRunnable::get);
                return executor;
            }

        };
    }

}
